package thinkinginjava.IO;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Directory {
	public static File[] local(File dir, final String regex) {
		return dir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {

				return name.matches(regex);
			}

		});

	}

	public static class TreeInfo implements Iterable<File> {
		public List<File> dirs = new ArrayList<File>(0);
		public List<File> files = new ArrayList<File>(0);

		@Override
		public Iterator<File> iterator() {
			return files.iterator();
		}

		public void addAll(TreeInfo tree) {
			dirs.addAll(tree.dirs);
			files.addAll(tree.files);
		}
		
		public String toString() {
			StringBuffer b = new StringBuffer();
			for(File dir : dirs) {
				b.append(dir.getName() + "\n");
			}
			for(File file : files) {
				b.append(file.getName() + "");
			}
			return b.toString();
		}
	}
	
	public static TreeInfo walk(File dir, String regex) {
		return recurseDirs(dir, regex);
	}
	
	public static TreeInfo walk(String dir, String regex) {
		return recurseDirs(new File(dir), regex);
	}
	
	public static TreeInfo walk(String dir) {
		return walk(dir, ".*");
	}
	
	public static TreeInfo walk(File dir) {
		return walk(dir, ".*");
	}

	static TreeInfo recurseDirs(File dir, String regex) {
		TreeInfo tree = new TreeInfo();
		for (File file : dir.listFiles()) {
			if (file.isDirectory()) {
				tree.dirs.add(file);
				tree.addAll(recurseDirs(file, regex));
			} else if (file.getName().matches(regex)) {
				tree.files.add(file);
			} 
		}
		return tree;
	}

	public static void main(String[] args) {
		TreeInfo b = Directory.walk("."); 
		System.out.println(b.toString());
	}
}
